# -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 20:50:38 2017

@author: tim
"""
import mysql.connector

class Database():
    user = ''
    password = ''
    database = ''
    def __init__(self, user, password,database):
        self.user = user
        self.password = password
        self.database = database
     

    def updateDatabase(self, tableName, data):
        keys = data.keys()
        columes = ''
        values = ''
        updateValues = ''
        for key in keys:
            columes = columes + key + ','
            values = values + data[key] + ','
            updateValues = updateValues + key + '=' + data[key] + ','
        columes = columes[0:-1]
        values = values[0:-1]
        updateValues = updateValues[0:-1]
        cmd = 'insert into '\
        +self.database\
        +'.'\
        + tableName \
        + ' (' + columes + ') values (' \
        + values \
        + ') ON DUPLICATE KEY UPDATE ' \
        + updateValues
        print cmd
        conn = mysql.connector.connect(user= self.user, password=self.password, database=self.database, use_unicode=True)
        cursor = conn.cursor()
        cursor.execute(cmd)
        conn.commit()
        cursor.close()
        cursor = conn.cursor()
        cursor.execute('select last_insert_id()')
        id = cursor.fetchall()
        conn.close()
        cursor.close()
        return id[0][0]
    
    
    def insert(self, tableName, data):
        if data.get('id', True) == True:
            return self.updateDatabase(tableName, data)
            
        else:
            return None
        
    def update(self, tableName, data):
        if data.get('id', True) == True:
            return None
        else:
            return self.updateDatabase(tableName, data)
        


def test():
    a = Database('root', '115257', 'audio')
    print a.insert( 'person', { 'name':"'lily'"})

if __name__ == '__main__':
    test()